import Mock from 'mockjs';
import {useMockStore} from "@/stores/MockDataBase.js";

// 创建内存数据库
const mockDatabase = (() => {
    // 生成用户数据
    const generateUsers = () => {
        return Mock.mock({
            'list|20-50': [
                {
                    'id|+1': 1,
                    'name': '@cname',
                    'email': '@email',
                    'phone': /1[3-9]\d{9}/,
                    'role': '@pick(["admin", "editor", "viewer"])',
                    'createdAt': '@datetime',
                    'avatar': '@image("100x100")',
                    'status|0-2': 0 // 0-正常, 1-禁用, 2-未激活
                }
            ]
        }).list;
    };

    return {
        users: generateUsers(),
        currentUser: null
    };
})();

/**
 * 用户模块Mock配置
 * @param {MockAdapter} mock - Mock适配器实例
 */
export default function(mock) {

    console.log(mockDatabase.users);

    // 获取用户列表（带分页）
    mock.onGet('/users').reply(config => {

        const { page = 1, size = 10 } = config.params;
        const start = (page - 1) * size;
        const end = start + size;
        const paginated = mockDatabase.users.slice(start, end);

        return [200, {
            code: 200,
            data: paginated,
            pagination: {
                page,
                size,
                total: mockDatabase.users.length,
                totalPages: Math.ceil(mockDatabase.users.length / size)
            }
        }];
    });

    // 获取单个用户
    mock.onGet(/\/users\/\d+$/).reply(config => {
        const userId = config.url.split('/').pop();
        const user = mockDatabase.users.find(u => u.id == userId);

        return user
            ? [200, { code: 200, data: user }]
            : [404, { code: 404, message: '用户不存在' }];
    });

    // 创建用户
    mock.onPost('/users').reply(config => {
        const newUser = JSON.parse(config.data);
        newUser.id = Math.max(...mockDatabase.users.map(u => u.id)) + 1;
        newUser.createdAt = new Date().toISOString();
        newUser.status = 0; // 新用户默认未激活

        mockDatabase.users.unshift(newUser);

        return [201, {
            code: 201,
            message: '用户创建成功',
            data: newUser
        }];
    });

    mock.onPost('/user/register/public').reply(config => {

        const userMock = useMockStore();

        const {phone, password, username, idCard} = JSON.parse(config.data);
        // 创建新用户
        const newUser = {
            id: mockDatabase.users.length + 1,
            phone,
            password,
            username,
            idCard,
            createdAt: new Date().toISOString(),
            status: 0 // 新用户默认激活
        };
        mockDatabase.users.push(newUser);

        userMock.setUsers( mockDatabase.users);

        // 模拟注册成功
        return [200, {
            code: 200,
            message: '注册成功',
            data: newUser
        }]
    });

    // 用户登录
    mock.onPost('/api/login').reply(config => {
        const useMock = useMockStore();

        console.log('login:',config.data);

        const { username, password } = JSON.parse(config.data);

        // 查找用户
        const user = useMock.findByUsername(username);

        console.log('user:',user);

        // 模拟登录失败场景
        if (!user){
            console.log('user not found');
            return [401, {
                code: 401,
                message: '用户名或密码错误'
            }]
        }
        if (user.status !== 0) return [403, {
            code: 403,
            message: user.status === 1 ? '账户已禁用' : '账户未激活，请验证邮箱'
        }];

        // 更新当前用户
        mockDatabase.currentUser = user;

        return [200, {
            code: 200,
            message: '登录成功',
            data: {
                token: `mock_jwt_token_${Date.now()}`,
                expires: 3600 * 24 * 7, // 7天有效期
                user
            }
        }];
    });

    // 获取当前用户
    mock.onGet('/currentUser').reply(() => {
        return mockDatabase.currentUser
            ? [200, { code: 200, data: mockDatabase.currentUser }]
            : [401, { code: 401, message: '未登录' }];
    });
}